﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using HISModels;
using HISModels.Entities;
using KeanuMvc.Reference;
using System.Configuration;
using System.IO;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using HISModels.ViewModel;

namespace HIS.Utils {

    public static class Helper {

        public static string DropDownOptions(KeanuMvc.Reference.ClientRestService clientService, string Selected, int GroupID) {
            string strResult = string.Empty;
            string strUri = Global.ServiceUriDictionary["optgroup"] + GroupID + Global.ServiceUriDictionary["requestformat"];

            StringReader stringReader = clientService.GetJson(strUri);
            List<SysOption> listOption = JsonConvert.DeserializeObject<List<SysOption>>(stringReader.ReadToEnd());

            List<object[]> listOptionItems = new List<object[]>();

            foreach (SysOption item in listOption) {
                listOptionItems.Add(new object[] { item.Id, item.DescValue });
            }

            strResult = KeanuMvc.Reference.Html.DropDown("StatusId", string.Empty, listOptionItems, Selected);
            listOptionItems.Clear();
            listOptionItems = null;
            stringReader.Dispose();
            return strResult;
        }

        public static T ToEnum<T>(this object value) {
            return (T)Enum.Parse(typeof(T), value.ToString());
        }

        public static string GetDoctorId() {
            string strUri = Global.ServiceUriDictionary["doctorid"] + GetUserId() + Global.ServiceUriDictionary["requestformat"];
            string doctorId = string.Empty;
            ClientRestService RestService = new ClientRestService();
            StringReader stringReader = RestService.GetJson(strUri);

            JObject o = JObject.Parse(stringReader.ReadToEnd());

            JArray aaDoctor = (JArray)o["Detail"];

            JObject oo = JObject.Parse(aaDoctor[0].ToString());
            doctorId = oo["doctorid"].ToString();
            return doctorId;
        }

        public static string GetUserId() {
            string encryptedTicket = string.Empty;
            string decryptUserId = string.Empty;
            try {
                encryptedTicket = KeanuMvc.Reference.CryptoString.Decrypt(HttpContext.Current.Session["userticketdata"].ToString());

                if (!string.IsNullOrEmpty(encryptedTicket))
                    decryptUserId = encryptedTicket.Split('|')[0];

            } catch { }

            return decryptUserId;
        }

        public static string ErrorMessage(string Message) {
            return "<div class='mws-form-message error'><h2>Errors!</h2><p>" + Message + "</p></div>";
        }

        public static string AttentionMessage(string Message) {
            return "<div class='message warning close'><h2>Attentions!</h2><p>" + Message + "</p></div>";
        }

        public static string SuccessMessage(string Message) {
            return "<div class='mws-form-message success'><h2>Congrulations!</h2><p>" + Message + "</p></div>";
        }

        public static string InformationMessage(string Message) {
            return "<div class='message information close'><h2>Information!</h2><p>" + Message + "</p></div>";
        }

        public static string WritePagination(int Start, string Parrams, int TotalRecord) {
            string strReturnValue = string.Empty;
            KeanuMvc.Reference.Pagination pagination = new KeanuMvc.Reference.Pagination();
            try {
                pagination.StartTag = "<p class=\"pagination\">";

                pagination.First = "<<";
                pagination.FirstBeginTag = "<span class=\"first\">";
                pagination.FirstEndTag = "</span>";

                pagination.Prev = "<";
                pagination.PrevBeginTag = "<span>";
                pagination.PrevEndTag = "</span>";

                pagination.NormalBeginTag = "<span>";
                pagination.NormalEndTag = "</span>";

                pagination.Last = ">>";
                pagination.LastBeginTag = "<span class=\"first\">";
                pagination.LastEndTag = "</span>";

                pagination.Next = ">";
                pagination.NextBeginTag = "<span>";
                pagination.NextEndTag = "</span>";

                pagination.CurrentSelectedBeginTag = "<span class=\"current\">";
                pagination.CurrentSelectedEndTag = "</span>";

                pagination.CloseTag = "</p>";
                strReturnValue = pagination.CreatePagination(Parrams, Start, TotalRecord, 10);
            } catch {
            } finally {
                pagination = null;
            }

            return strReturnValue;
        }

        public static string GenerateNavigationAdmin(KeanuMvc.Reference.ClientRestService clientService, int GroupID) {
            return GenerateNavigation(true, clientService, GroupID);
        }

        public static string GenerateNavigationForUser(KeanuMvc.Reference.ClientRestService clientService, int GroupID) {
            return GenerateNavigation(false, clientService, GroupID);
        }

        #region Private Method Navigation
        private static string GenerateNavigation(bool IsAdmin, KeanuMvc.Reference.ClientRestService clientService, int GroupID) {
            string strNavigation = @"";

            IList<HIS.Utils.NavigationCustom> topLevelNavigations = TreeHelper.ConvertToForest(SetNavigationObject(clientService, GroupID));

            foreach (HIS.Utils.NavigationCustom topLevelNavigation in topLevelNavigations) {
                if (IsAdmin) {
                    RenderNavigationAdmin(topLevelNavigation, ref strNavigation);
                } else {
                    RenderNavigationForUser(topLevelNavigation, ref strNavigation);
                }
            }
            //strNavigation += "</ul>";
            return strNavigation;
        }

        private static List<HIS.Utils.NavigationCustom> SetNavigationObject(KeanuMvc.Reference.ClientRestService clientService, int GroupID) {
            string strUri = Global.ServiceUriDictionary["navsgroup"] + GroupID + Global.ServiceUriDictionary["requestformat"];
            StringReader stringReader = clientService.GetJson(strUri);
            List<HISModels.Entities.SysNavigation> ListSysNavigation = JsonConvert.DeserializeObject<List<SysNavigation>>(stringReader.ReadToEnd());
            List<HIS.Utils.NavigationCustom> navigationCustom = new List<HIS.Utils.NavigationCustom>();

            foreach (HISModels.Entities.SysNavigation item in ListSysNavigation) {
                HIS.Utils.NavigationCustom c = new HIS.Utils.NavigationCustom();
                c.Id = item.Id;
                c.Name = item.DescValue;
                c.GroupId = item.NavigationGroupId;
                c.Url = item.Url;
                c.Order = item.SeqOrder;
                if (item.ParentId != 0) {
                    c.Parent = new HIS.Utils.NavigationCustom();
                    c.Parent.Id = item.ParentId;
                }
                navigationCustom.Add(c);
            }
            return navigationCustom;
        }

        private static void RenderNavigationAdmin(HIS.Utils.NavigationCustom pNavigationCustom, ref string pStrNavigation) {

            pStrNavigation += "<li>" + pNavigationCustom.Order + ". " + pNavigationCustom.Name + "<a class='tooltip' title='Edit Record' href='/admins/navigationgroup/editnavigationsetting/?groupid=" + pNavigationCustom.GroupId + "&id=" + pNavigationCustom.Id + "'><img src='/images/icons/pencil.png'/></a>" + "<a class='tooltip confirm' title='Delete Record' confirmdelete='Are you want to delete this record?' href='/admins/navigationgroup/deletenavigationsetting/?groupid=" + pNavigationCustom.GroupId + "&id=" + pNavigationCustom.Id + "'><img src='/images/icons/eraser.png'/></a> " + pNavigationCustom.Url;

            if (pNavigationCustom.Children.Count > 0) {
                pStrNavigation += "<ul>";
                foreach (HIS.Utils.NavigationCustom child in pNavigationCustom.Children) RenderNavigationAdmin(child, ref pStrNavigation);
                pStrNavigation += "</ul>";
            }
            pStrNavigation += "</li>";
        }

        private static void RenderNavigationForUser(HIS.Utils.NavigationCustom pNavigationCustom, ref string pStrNavigation) {
            if (pNavigationCustom.Url != string.Empty) {
                pStrNavigation += "<li id='liid_" + pNavigationCustom.Id + "'><a id='ahrefid_" + pNavigationCustom.Id + "' href='" + pNavigationCustom.Url + "'>" + pNavigationCustom.Name + "</a>";
            } else {
                pStrNavigation += "<li id='liid_" + pNavigationCustom.Id + "'><a>" + pNavigationCustom.Name + "</a>";
            }
            
            if (pNavigationCustom.Children.Count > 0) {
                pStrNavigation += "<ul class='closed' id='ulid_" + pNavigationCustom.Id + "'>";
                foreach (HIS.Utils.NavigationCustom child in pNavigationCustom.Children) RenderNavigationForUser(child, ref pStrNavigation);
                pStrNavigation += "</ul>";
            }
            pStrNavigation += "</li>";
        }
        #endregion

        public static object SetNullToEmptyString(this object obj) {
            var properties = from p in obj.GetType().GetProperties()
                             where p.PropertyType == typeof(string) &&
                             p.CanRead && p.CanWrite
                             select p;
            foreach (var property in properties) {
                var value = (string)property.GetValue(obj, null);
                if (value == null) {
                    property.SetValue(obj, string.Empty, null);
                }
            }
            return obj;
        }

        public static string GetIdentityCardType(string ddName, string selectedValue) {
            return LoadMasterFile(ddName, string.Empty, true, selectedValue, "RefIdentityCardType");
        }

        public static string GetSalutation(string ddName, string selectedValue) {
            string filePath = HttpContext.Current.Request.PhysicalApplicationPath + "Cache\\Ref\\Salutations.txt";
            string[] lines = System.IO.File.ReadAllLines(filePath);

            List<object[]> listDropdown = new List<object[]>();
            listDropdown.Add(new object[] { "", "-Title-" });
            for (int i = 0; i < lines.Count(); i++) {
                listDropdown.Add(new object[] { lines[i].Split('|')[0], lines[i].Split('|')[1] });
            }
            string strDropdown = string.Empty;
            strDropdown = Html.DropDown(ddName, "class='required'", listDropdown, selectedValue);
            return strDropdown;

        }
        public static string GetDoctorSalutation(string ddName, string selectedValue) {
            string filePath = HttpContext.Current.Request.PhysicalApplicationPath + "Cache\\Ref\\RefDoctorSalutation.txt";
            string[] lines = System.IO.File.ReadAllLines(filePath);

            List<object[]> listDropdown = new List<object[]>();
            listDropdown.Add(new object[] { "", "-Title-" });
            for (int i = 0; i < lines.Count(); i++) {
                listDropdown.Add(new object[] { lines[i].Split('|')[0], lines[i].Split('|')[1] });
            }
            string strDropdown = string.Empty;
            strDropdown = Html.DropDown(ddName, "class='required'", listDropdown, selectedValue);
            return strDropdown;
        }
        public static string GetDoctorTitle(string ddName, string selectedValue) {
            return LoadMasterFile(ddName, "class='required'", true, selectedValue, "DoctorTitle");

        }
       
        public static string GetOccupation(string ddName, string selectedValue) {
            return LoadMasterFile(ddName, string.Empty, true, selectedValue, "RefOccupations");

        }

        public static string GetMaritalStatus(string ddName, string selectedValue) {
            return LoadMasterFile(ddName, string.Empty, true, selectedValue, "RefMaritals");
        }

        public static string GetReligion(string ddName, string selectedValue) {
            return LoadMasterFile(ddName, string.Empty, true, selectedValue, "RefReligions");
        }

        private static string LoadMasterFile(string ddName, string attribute, bool defaultSelect, string selectedValue, string FileName) {
            string filePath = HttpContext.Current.Request.PhysicalApplicationPath + "Cache\\Ref\\" + FileName + ".txt";
            string[] lines = System.IO.File.ReadAllLines(filePath);

            List<object[]> listDropdown = new List<object[]>();
            if (defaultSelect) {
                listDropdown.Add(new object[] { "", "--Select--" });
            }
            for (int i = 0; i < lines.Count(); i++) {
                listDropdown.Add(new object[] { lines[i].Split('|')[0], lines[i].Split('|')[1] });
            }
            string strDropdown = string.Empty;
            strDropdown = Html.DropDown(ddName, attribute, listDropdown, selectedValue);
            return strDropdown;
        }

        public static string GetEthnic(string ddName, string selectedValue) {
            return LoadMasterFile(ddName, string.Empty, true, selectedValue, "RefEthnicities");
        }

        public static string GetBloodType(string ddName,string additionalAttr, string selectedValue) {
            return LoadMasterFile(ddName, additionalAttr, true, selectedValue, "RefType");
        }
       
        public static string GetDays(string ddName, string selectedValue) {
            return LoadMasterFile(ddName, "class='required'", true, selectedValue, "RefDayOfWeeks");
        }

        public static string GetCountry(string ddName, string selectedValue) {
            return LoadMasterFile(ddName, string.Empty, true, selectedValue, "RefCountries");
        }
        public static string GetGender(string ddName, string additionalTag, string selectedValue)
        {
            return LoadMasterFile(ddName, additionalTag, true, selectedValue, "RefGender");
        }

        public static string GetPatientPayer(string ddName, string additionalTag, string selectedValue) {
            string filePath = HttpContext.Current.Request.PhysicalApplicationPath + "Cache\\Ref\\RefPayerCategories.txt";
            string[] lines = System.IO.File.ReadAllLines(filePath);

            List<object[]> listDropdown = new List<object[]>();
            listDropdown.Add(new object[] { "", "*" });
            for (int i = 0; i < lines.Count(); i++) {
                listDropdown.Add(new object[] { lines[i].Split('|')[0], lines[i].Split('|')[1] });
            }
            string strDropdown = string.Empty;
            strDropdown = Html.DropDown(ddName, additionalTag, listDropdown, selectedValue);
            return strDropdown;
        }

        public static string GetFamilyRelative(string ddName, string selectedValue) {
            return LoadMasterFile(ddName, string.Empty, true, selectedValue, "RefFamilyRelativeTypes");
        }

        public static string GetRelative(string ddName, string selectedValue) {
            return LoadMasterFile(ddName, string.Empty, true, selectedValue, "RefOtherRelativeTypes");
        }

        public static string GetEducation(string ddName, string selectedValue) {
            return LoadMasterFile(ddName, string.Empty, true, selectedValue, "RefEducations");
        }

        public static string GetMinutePerSlotDoctor(string ddName, string selectedValue) {
            return LoadMasterFile(ddName, "class='required'", true, selectedValue, "RefMinutePerSlot");
        }

        //flag
        public static string DropDownSpecialist(string name,string Selected, bool isDefaultSelect, ClientRestService baseRestService) {
            StringReader stringReaderDropDown = null;
            string strResult = string.Empty;
            string Name = string.Empty;
            string strUri = "";

            strUri = Global.ServiceUriDictionary["doctorspecialist"] + Global.ServiceUriDictionary["requestformat"];
            try {
                stringReaderDropDown = baseRestService.GetJson(strUri);
                List<RefSpecialist> listSp = JsonConvert.DeserializeObject<List<RefSpecialist>>(stringReaderDropDown.ReadToEnd());
                List<object[]> activeArr = new List<object[]>();

                if (isDefaultSelect) {
                    activeArr.Add(new object[] { 0, Name = "--Select--" });
                } else {
                    activeArr.Add(new object[] { 0, Name = "- All Specialist -" });
                }
                

                foreach (RefSpecialist item in listSp) activeArr.Add(new object[] { item.Id, Name = item.CodeValue+" - "+item.NameValue });

                strResult = KeanuMvc.Reference.Html.DropDown(name, string.Empty, activeArr, Selected);
                activeArr.Clear();
                activeArr = null;
            } catch {
            } finally {
                stringReaderDropDown.Dispose();
            }
            return strResult;
        }

        public static string GetDocSpecialistVal(string name, string Selected, string AdditionalAttr, bool isDefaultSelect, ClientRestService baseRestService) {
            StringReader stringReaderDropDown = null;
            string strResult = string.Empty;
            string Name = string.Empty;
            string strUri = "";

            strUri = Global.ServiceUriDictionary["doctorspecialist"] + Global.ServiceUriDictionary["requestformat"];
            try {
                stringReaderDropDown = baseRestService.GetJson(strUri);
                List<RefSpecialist> listSp = JsonConvert.DeserializeObject<List<RefSpecialist>>(stringReaderDropDown.ReadToEnd());
                List<object[]> activeArr = new List<object[]>();

                if (isDefaultSelect) {
                    activeArr.Add(new object[] { "", Name = "--Select--" });
                } else {
                    activeArr.Add(new object[] { "", Name = "- All Specialist -" });
                }
                foreach (RefSpecialist item in listSp) activeArr.Add(new object[] { item.NameValue, Name = item.CodeValue+" - "+ item.NameValue });

                strResult = KeanuMvc.Reference.Html.DropDown(name, AdditionalAttr, activeArr, Selected);
                activeArr.Clear();
                activeArr = null;
            } catch {
            } finally {
                stringReaderDropDown.Dispose();
            }
            return strResult;
        }

        public static string GetDropDownHospital(string name, string Selected, bool isDefaultSelect, ClientRestService baseRestService) {
            StringReader stringReaderDropDown = null;
            string strResult = string.Empty;
            string Name = string.Empty;
            string strUri = "";

            strUri = Global.ServiceUriDictionary["hospital"] + Global.ServiceUriDictionary["requestformat"];
            try {
                stringReaderDropDown = baseRestService.GetJson(strUri);
                List<RefHu> listSp = JsonConvert.DeserializeObject<List<RefHu>>(stringReaderDropDown.ReadToEnd());
                List<object[]> activeArr = new List<object[]>();

                if (isDefaultSelect) {
                    activeArr.Add(new object[] { 0, Name = "--Select--" });
                } else {
                    activeArr.Add(new object[] { 0, Name = "- All Hospital-" });
                }


                foreach (RefHu item in listSp) activeArr.Add(new object[] { item.Id, Name = item.NameValue });

                strResult = KeanuMvc.Reference.Html.DropDown(name, string.Empty, activeArr, Selected);
                activeArr.Clear();
                activeArr = null;
            } catch {
            } finally {
                stringReaderDropDown.Dispose();
            }
            return strResult;
        }

        public static string GetDropDownWard(string name, string Selected, bool isDefaultSelect, ClientRestService baseRestService) {
            StringReader stringReaderDropDown = null;
            string strResult = string.Empty;
            string Name = string.Empty;
            string strUri = "";

            strUri = Global.ServiceUriDictionary["ward"] + Global.ServiceUriDictionary["requestformat"];
            try {
                stringReaderDropDown = baseRestService.GetJson(strUri);
                List<HuWard> listSp = JsonConvert.DeserializeObject<List<HuWard>>(stringReaderDropDown.ReadToEnd());
                List<object[]> activeArr = new List<object[]>();

                if (isDefaultSelect) {
                    activeArr.Add(new object[] { 0, Name = "--Select--" });
                } else {
                    activeArr.Add(new object[] { 0, Name = "- All Ward-" });
                }


                foreach (HuWard item in listSp) activeArr.Add(new object[] { item.Id, Name = item.NameValue });

                strResult = KeanuMvc.Reference.Html.DropDown(name, string.Empty, activeArr, Selected);
                activeArr.Clear();
                activeArr = null;
            } catch {
            } finally {
                stringReaderDropDown.Dispose();
            }
            return strResult;
        }
        public static string GetDropDownRoom(string name, string Selected, bool isDefaultSelect, ClientRestService baseRestService) {
            StringReader stringReaderDropDown = null;
            string strResult = string.Empty;
            string Name = string.Empty;
            string strUri = "";

            strUri = Global.ServiceUriDictionary["room"] + Global.ServiceUriDictionary["requestformat"];
            try {
                stringReaderDropDown = baseRestService.GetJson(strUri);
                List<HuRoom> listSp = JsonConvert.DeserializeObject<List<HuRoom>>(stringReaderDropDown.ReadToEnd());
                List<object[]> activeArr = new List<object[]>();

                if (isDefaultSelect) {
                    activeArr.Add(new object[] { 0, Name = "--Select--" });
                } else {
                    activeArr.Add(new object[] { 0, Name = "- All Room-" });
                }


                foreach (HuRoom item in listSp) activeArr.Add(new object[] { item.Id, Name = item.NameValue });

                strResult = KeanuMvc.Reference.Html.DropDown(name, string.Empty, activeArr, Selected);
                activeArr.Clear();
                activeArr = null;
            } catch {
            } finally {
                stringReaderDropDown.Dispose();
            }
            return strResult;
        }

        public static string GetAge(DateTime dob) {
            DateTime dateOfBirth = dob;
            DateTime currentDate = DateTime.Now;

            int ageInYears = 0;
            int ageInMonths = 0;
            int ageInDays = 0;
            string yearString = "";
            string monthString = "";
            string dayString = "";
            string ageString = "";

            ageInYears = currentDate.Year - dateOfBirth.Year;

            if (currentDate.Month >= dateOfBirth.Month)
                ageInMonths = currentDate.Month - dateOfBirth.Month;
            else {
                ageInYears--;
                ageInMonths = 12 + currentDate.Month - dateOfBirth.Month;
            }

            if (currentDate.Day >= dateOfBirth.Day)
                ageInDays = currentDate.Day - dateOfBirth.Day;
            else {
                ageInMonths--;
                ageInDays = 31 + currentDate.Day - dateOfBirth.Day;

                if (ageInMonths < 0) {
                    ageInMonths = 11;
                    ageInYears--;
                }
            }

            if (ageInYears > 1) yearString = " (years)";
            else yearString = " (year)";
            if (ageInMonths > 1) monthString = " (months)";
            else monthString = " (month)";
            if (ageInDays > 1) dayString = " (days)";
            else dayString = " (day)";


            if ((ageInYears > 0) && (ageInMonths > 0) && (ageInDays > 0))
                ageString = ageInYears + yearString + ", " + ageInMonths + monthString + ", and " + ageInDays + dayString + " old";
            else if ((ageInYears == 0) && (ageInMonths == 0) && (ageInDays > 0))
                ageString = ageInDays + dayString + " old";
            else if ((ageInYears > 0) && (ageInMonths == 0) && (ageInDays == 0))
                ageString = ageInYears + yearString + " old";
            else if ((ageInYears > 0) && (ageInMonths > 0) && (ageInDays == 0))
                ageString = ageInYears + yearString + " and " + ageInMonths + monthString + " old";
            else if ((ageInYears == 0) && (ageInMonths > 0) && (ageInDays > 0))
                ageString = ageInMonths + monthString + " and " + ageInDays + dayString + " old";
            else if ((ageInYears > 0) && (ageInMonths == 0) && (ageInDays > 0))
                ageString = ageInYears + yearString + " and " + ageInDays + dayString + " old";
            else if ((ageInYears == 0) && (ageInMonths > 0) && (ageInDays == 0))
                ageString = ageInMonths + monthString + " old";
            else ageString = "Invalid Format Date";


            return ageString;
        }
    }

}